package game.players.goalkeeper.opp;

import com.uqbar.vainilla.DeltaState;
import com.uqbar.vainilla.appearances.Animation;
import com.uqbar.vainilla.appearances.Appearance;
import com.uqbar.vainilla.appearances.Sprite;

import game.ball.SoccerBall;
import game.players.SoccerPlayer;
import game.players.goalkeeper.GoalkeeperState;

public class WalkingToTheBallOppGoalkeeper extends GoalkeeperState {

	private Appearance appearance = new Animation(0.3,
			Sprite.fromImage("/images/arquero_arco.png").crop(21,11,84,77),
			Sprite.fromImage("/images/arquero_arco.png").crop(112,13,84,77),
			Sprite.fromImage("/images/arquero_arco.png").crop(200,13,84,79));
	
	public WalkingToTheBallOppGoalkeeper(SoccerPlayer player) {
		super(player);
		player.setAppearance(this.appearance);
	}

	@Override
	public void update(DeltaState deltaState) {
		SoccerBall ball = this.getGoalkeeper().getScene().getSoccerBall();
		this.advanceToBall(ball);
		if(this.collidesAgainstBall()){
			this.getGoalkeeper().takeTheBall();
		}
		if(this.getGoalkeeper().isMisplaced())
			this.returnToTheArc();			
	}
	
	public void advanceToBall(SoccerBall ball) {
		double vectorI = ball.getX() - this.getPlayer().getX() + this.getPlayer().getFeetWidth();
		double vectorJ = ball.getY() - this.getPlayer().getY() - this.getPlayer().getAppearance().getHeight() + this.getPlayer().getFeetHeight();		
		double module = Math.sqrt(Math.pow(vectorI, 2) + Math.pow(vectorJ, 2));		
		double versorI = vectorI / module;
		double versorJ = vectorJ / module;		
		this.getPlayer().move(versorI * this.getPlayer().getMovementSpeed() / 2, versorJ * this.getPlayer().getMovementSpeed() / 2);
	}

	@Override
	public boolean isWithBall() {
		return false;
	}

	@Override
	public boolean isRight() {
		return false;
	}
	
	public void returnToTheArc() {
		this.getGoalkeeper().setState(new ReturningToTheArcOppGoalkeeper(this.getGoalkeeper()));
	}

}
